// @flow
import React from 'react'
import { DatePicker, Form, Input, Select, Button, message } from 'antd'
import universalFetch from 'store/modules/fetch'
import styles from './Home.css'
import moment from 'moment'
const { RangePicker } = DatePicker

type Props = {
  form: Object,
  history: Object
}

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type States = {
  deviceData: Array<any>,
  FaultData: Object,
  loading: boolean
}
class FaultAdd extends React.Component {
  props: Props
  state: States
  goBack: Function
  getDeviceData: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      deviceData: [],
      FaultData: {},
      loading: false
    }

    this.goBack = this.goBack.bind(this)
    this.getDeviceData = this.getDeviceData.bind(this)
  }

  getDeviceData () {
    universalFetch(`${__SERVICE_API__}device/devices?pageSize=20000`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        deviceData: json.result
      })
    })
    .catch((error) => {
      console.error(error)
    })
  }

  goBack () {
    const { history } = this.props
    history.push('/business/fault')
  }

  /**
   * 提交表单
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const rangeTime = fieldsValue.rangeTime
      const values = {
        ...fieldsValue,
        'componentId': 0, // 后台设定的必须传的值，但没有实际意义
        'startTime': rangeTime[0].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        'endTime': rangeTime[1].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ')
      }
      const { FaultData } = this.state
      universalFetch(`${__SERVICE_API__}device/events/faults/${FaultData.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(values)
      })
        .then(res => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            loading: false
          })
          message.success('维修记录修改成功')
          this.props.history.push('/business/fault')
        })
        .catch((error) => {
          console.error(error)
          message.error('维修记录修改失败')
          this.setState({
            loading: false
          })
        })
    })
  }
  componentWillMount () {
    this.getDeviceData()
    const { data } = this.props.history.location.state
    this.setState({
      FaultData: data
    })
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { loading, deviceData, FaultData } = this.state
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label='设备'>
            {getFieldDecorator('deviceId', {
              rules: [
                { required: true, message: '请选择设备' }
              ],
              initialValue: FaultData.deviceId
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择设备'>
                {
                  deviceData.map((d, i) => {
                    return <Option key={i} value={d.id}>{d.name}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='事件名称'>
            {getFieldDecorator('eventName', {
              rules: [
                { required: true, message: '请输入事件名称', whitespace: true }
              ],
              initialValue: FaultData.eventName
            })(
              <Input placeholder='请输入事件名称' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='事件类型' hasFeedback>
            {getFieldDecorator('eventType', {
              rules: [
                { required: true, message: '请输入事件类型', whitespace: true }
              ],
              initialValue: FaultData.eventType
            })(
              <Input placeholder='请输入事件类型' disabled />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='起止日期'>
            {getFieldDecorator('rangeTime', {
              rules: [
                { required: true, message: '请选择起止日期' }
              ],
              initialValue: [moment(FaultData.startTime), moment(FaultData.endTime)]
            })(
              <RangePicker size='default' />
            )}
          </FormItem>
          {
            // <FormItem {...formItemLayout} label='开始时间'>
            //   {getFieldDecorator('startTime', {
            //     rules: [
            //       { required: true, message: '请选择开始时间' }
            //     ],
            //     initialValue: moment(FaultData.startTime)
            //   })(
            //     <DatePicker placeholder='请选择开始时间' />
            //   )}
            // </FormItem>
            // <FormItem {...formItemLayout} label='结束时间'>
            //   {getFieldDecorator('endTime', {
            //     rules: [
            //       { required: true, message: '请选择结束时间' }
            //     ],
            //     initialValue: moment(FaultData.endTime)
            //   })(
            //     <DatePicker placeholder='请选择结束时间' />
            //   )}
            // </FormItem>
          }
          <FormItem {...formItemLayout} label='负责人'>
            {getFieldDecorator('owner', {
              rules: [
                { required: true, message: '请输入负责人', whitespace: true }
              ],
              initialValue: FaultData.owner
            })(
              <Input placeholder='请输入负责人' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='处理方法'>
            {
              getFieldDecorator('dealMethod', {
                initialValue: FaultData.dealMethod
              })(
                <Input placeholder='请输入处理方法' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='状态'>
            {
              getFieldDecorator('status', {
                initialValue: FaultData.status
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择状态'>
                  <Option key='1' value='已解决'>已解决</Option>
                  <Option key='2' value='未解决'>未解决</Option>
                  <Option key='3' value='生成工单'>生成工单</Option>
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='描述' hasFeedback>
            {getFieldDecorator('detail', {
              initialValue: FaultData.detail
            })(
              <Input placeholder='请填写描述' />
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary' htmlType='submit' size='large'
              loading={loading}
              >修改</Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={this.goBack}
              >返回</Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

export default Form.create()(FaultAdd)
